package com.bash.carrep.business;

import com.bash.carrep.business.exception.LoginExeption;
import com.bash.carrep.dao.enties.Login;
import com.bash.carrep.dao.general.CRUD;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 * Gestion de la procedure de login a l'application
 * @author bash
 */
public class LoginBusiness {

    static String errMsg = "Login ou mot de passe invalide !";
    static CRUD crud = CRUD.getInstance();

    public static Login doLogin(Login login) throws LoginExeption {

        String username = login.getUsername();
        String password = login.getPassword();

        String querryQL = "SELECT l FROM Login l WHERE l.username = :username and l.password=:password";

        Login loginx = null;

        try {

            Query q = crud.getEntityManager().createQuery(querryQL);

            q.setParameter("username", username);
            q.setParameter("password", password);

            crud.start();
            loginx = (Login) crud.getSingle(q);
            crud.stop();
// TODO Handle a communication problem !!
            if (loginx == null) {
                throw new LoginExeption(errMsg);
            }
        } catch (NoResultException ex) {
            throw new LoginExeption(errMsg);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return loginx;

    }
}
